package com.plugin.wly.amaplocation;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationClientOption.AMapLocationProtocol;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 高德地图定位
 */
public class AmapLocationPlugin extends CordovaPlugin {

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private CallbackContext callbackContext = null;
    private Context context;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("getLocation")) {		//高德地图定位
            this.callbackContext = callbackContext;
            startSingleLocation(context);
            PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
            r.setKeepCallback(true);
            callbackContext.sendPluginResult(r);
            return true;
        }
        else if (action.equals("coolMethod")) {
            String message = args.getString(0);
            this.coolMethod(message, callbackContext);
            return true;
        }
        return false;
    }

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        context = this.cordova.getActivity().getApplicationContext();
        super.initialize(cordova, webView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    private void startSingleLocation(Context context) {
        //初始化client
        locationClient = new AMapLocationClient(context);
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
        // 启动定位
        locationClient.stopLocation();
        locationClient.startLocation();
    }
    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                //StringBuffer sb = new StringBuffer();
                SimpleDateFormat formatStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if(location.getErrorCode() == 0){
                    int locationType = location.getLocationType();
                    double longitude = location.getLongitude();
                    double latitude = location.getLatitude();
                    float accuracy = location.getAccuracy();
                    String provider = location.getProvider();
                    double speed = location.getSpeed();
                    double bearing = location.getBearing();
                    String country = location.getCountry();
                    String province = location.getProvince();
                    String city = location.getCity();
                    String cityCode = location.getCityCode();
                    String district = location.getDistrict();
                    String adCode = location.getAdCode();
                    String address = location.getAddress();
                    String poiName = location.getPoiName();
                    String locationTime = formatStr.format(new Date(location.getTime()));
                    JSONObject jo = new JSONObject();
                    try{
                        jo.put("locationType",locationType);
                        jo.put("longitude",longitude);
                        jo.put("latitude",latitude);
                        jo.put("accuracy", accuracy);
                        jo.put("provider",provider);
                        jo.put("speed",speed);
                        jo.put("bearing",bearing);
                        jo.put("country",country);
                        jo.put("province",province);
                        jo.put("city",city);
                        jo.put("cityCode",cityCode);
                        jo.put("district",district);
                        jo.put("adCode",adCode);
                        jo.put("address",address);
                        jo.put("poiName",poiName);
                        jo.put("locationTime",locationTime);
                        callbackContext.success(jo);

                        //WIFI开关：location.getLocationQualityReport().isWifiAble() ? "开启":"关闭"
                        //GPS状态：getGPSStatusString(location.getLocationQualityReport().getGPSStatus())
                        //GPS星数：location.getLocationQualityReport().getGPSSatellites()
                        //定位之后的回调时间
                        //long callbackTime = System.currentTimeMillis();
                        //Date date = new Date(callbackTime);
                        //回调时间: formatStr.format(date);
                    }
                    catch (JSONException e){
                        jo = null;
                        callbackContext.error("定位失败，定位数据转换json失败");
                    }
                } else {
                    //错误码:location.getErrorCode()
                    //错误信息:location.getErrorInfo()
                    //错误描述:location.getLocationDetail()
                    callbackContext.error(location.getErrorInfo());
                }
            } else {
                callbackContext.error("定位失败，location is null");
            }
        }
    };


    /**
     * 获取GPS状态的字符串
     * @param statusCode GPS状态码
     * @return
     */
    private String getGPSStatusString(int statusCode){
        String str = "";
        switch (statusCode){
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }

    /**
     * 默认的定位参数
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        //mOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);//签到模式，配置此项后下方的配置注释掉
        mOption.setLocationMode(AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        // mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        // AMapLocationClientOption.setLocationProtocol(AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        // mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        // mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        // mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}
